import 'package:get/get.dart';
import 'dart:core';
import 'package:flutter_my_picker/flutter_my_picker.dart';
import '../../../utils/Settings.dart';
import '../../../utils/Utils.dart';
import '../../form/LFormLogic.dart';
import '../../get/MyController.dart';
import 'LFormTimeState.dart';

class LFormTimeLogic extends MyController{


  final state = LFormTimeState();

  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData;
    state.defaultText = "";
    state.betweenSign = betweenSign??"";
    state.formTag = formTag;
    state.formType = formType;

    //是否有默认值
    if(!Utils.isEmpty(state.formData['${state.formItem["field"]}${state.betweenSign}'])){
      state.defaultText = state.formData['${state.formItem["field"]}${state.betweenSign}'];
    }
    update();
  }

  dynamic onValidator(v){
    //非空验证
    if (state.formItem["required"] == true && (v == null || v.isEmpty || v.trim().isEmpty)) {
      return "${state.formItem["label"]}不能为空";
    }
    return null;
  }

  void onSelected(date){
    state.defaultText = "${date.hour<10?'0${date.hour}':date.hour}:${date.minute<10?'0${date.minute}':date.minute}";
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = state.defaultText;
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.defaultText});
    }
    update();
  }

  onCancel(){
    state.defaultText="";
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':null});
    }
    update();
  }

  void showDataPicker(context) {
    MyPicker.showPicker(
      context: context,
      current: state.formData['${state.formItem["field"]}${state.betweenSign}']??DateTime.now(),
      mode: MyPickerMode.time,
      start: DateTime(state.formItem['firstDate']??DateTime.now().year-5),
      end: DateTime(state.formItem['lastDate']??DateTime.now().year+5),
      onConfirm:(date) {
        onSelected(date);
      },
      onCancel: (){
        onCancel();
      }
    );
  }

  ///如果是QUERYFORM 重置，需要将显示值清空
  @override
  void reset(){
    state.defaultText="";
    update();
  }

}